import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { retry } from 'rxjs/operators';

declare var base: any;
declare var security: any;
declare var form: any;

@Component({
  templateUrl: './tenant.token.html'
})
export class TenantTokenComponent implements OnInit {

  // 是否显示
  interfaceVisible = false;
  // 是否更新令牌
  updateToken = 'false';
  // 令牌
  token: any = {};
  // 加载中
  isLoading = false;
  // 当前授权接口
  ifpower = [];
  // 接口字典
  sysDic: any;

  constructor(private http: HttpClient) {
    this.sysDic = new form.DictionaryService('p_sys_service');
    this.sysDic.loadAll();
  }

  ngOnInit() {
    const jwts = security.SecurityService.jwt;
    const url = base.BaseService.getHostUrl() + '/tenantuser/getToken';
    const obsData = this.http.post<any>(url, '', { headers: new HttpHeaders({ jwt: jwts }) })
      .pipe(retry(1));
    this.isLoading = true;
    debugger
    obsData.subscribe(
      (data) => {
        this.isLoading = false;
        if (data.data === null) {
          this.token = {};
          this.ifpower = [];
        } else {
          this.token = data.data;
          this.ifpower = this.token.ifpower;
        }
      },
      () => {
        this.isLoading = false;
        this.token = {};
        this.ifpower = [];
      }
    );
  }

  editInterface() {
    this.interfaceVisible = true;
  }

  saveInterface() {
    this.isLoading = true;
    const jwts = security.SecurityService.jwt;
    const url = base.BaseService.getHostUrl() + '/tenantuser/regToken/' + this.updateToken;
    const obsData = this.http.post<any>(url, this.ifpower, { headers: new HttpHeaders({ jwt: jwts }) })
      .pipe(retry(1));
    obsData.subscribe(
      (data) => {
        if (data.data === null) {
          this.token = {};
          this.ifpower = [];
        } else {
          this.token = data.data;
          this.ifpower = this.token.ifpower;
        }
        this.interfaceVisible = false;
        this.isLoading = false;
      },
      () => {
        this.interfaceVisible = false;
        this.isLoading = false;
      }
    );
  }

  closeInterface() {
    this.interfaceVisible = false;
  }

  checked(e, s: any[]) {
    const id = e.node.key;
    if (e.node.isChecked) {
      if (s.indexOf(id) === -1) {
        s.push(id);
      }
    } else {
      if (s.concat(id)) {
        s.splice(s.indexOf(id), 1);
      }
    }
  }
}
